<?php

namespace App\Http\Controllers\AdminApi;

use App\Models\VueAdmin as Admin;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Exception;

class AuthController extends Controller
{
    /**
     * Login
     */
    public function login(Request $request)
    {
        try {
            if ($request->isMethod('post')) {
                $username = trim($request->input('username'));
                $password = trim($request->input('password'));
                $remember = $request->input('remember');

                if (!$username) {
                    throw new Exception('登录名不能为空！');
                }
                if (!$password) {
                    throw new Exception('密码不能为空！');
                }

                $adminInfo = Admin::where('username', $username)->first();
                if (!$adminInfo) {
                    throw new Exception('您的用户名不存在！');
                }
                if (!password_verify($password, $adminInfo['password'])) {
                    throw new Exception('密码错误！');
                }
                $captcha_code = trim($request->input('captcha_code'));
                $captcha_key = $request->input('captcha_key') ?? '';
                if ($captcha_code) {
                    $verifyObj = new \App\Services\Verify();
                    if (!$verifyObj->check($captcha_code, $captcha_key)) {
                        throw new Exception('验证码错误！');
                    }
                }

                $adminInfo = Admin::formatItem($adminInfo);

                $code = 200;
                $msg = '登录成功';

                $token = md5(time() . uniqid(). mt_rand(1000, 9999));
                $token_expire = time() + 3600*6;
                // 记住密码
                if ($remember) {
                    $token_expire = time() + 3600*24*7;
                }

                $origin = $request->header('origin');
                if (strstr($origin, 'http://127.0.0.1') !== false || strstr($origin, 'http://localhost')) {
                    // 跨域不能用session(跨域sessionid每次都会变，不能用session)
                    // 记录登录时间及IP等信息
                    $data = [
                        'last_login_time' => time(),
                        'last_login_ip' => get_IP(),
                        'token' => $token,
                        'token_expire' => $token_expire
                    ];
                    $record = Admin::where('id', $adminInfo['id'])->update($data);
                    if (!$record) {
                        throw new Exception('服务异常，请重新登录！');
                    }
                } else {
                    $adminInfo['token'] = $token;
                    $adminInfo['token_expire'] = $token_expire;
                    session('admin', $adminInfo); //
                    if ($remember) {
                        cookie('admin', json_encode($adminInfo), $token_expire);
                    }
                }
            } else {
                throw new Exception('请求方式不正确');
            }
        } catch (Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }

        return api_response($code, $msg, [
            'token' => $token ?? ''
        ]);
    }

    /**
     * Logout
     */
    public function logout(Request $request)
    {
        $token = $request->input('token');
        $data = [
            'token' => '',
            'token_expire' => 0
        ];
        $result = Admin::where('token', $token)->update($data);
        if ($result === false) {
            return api_response(0, 'Error', []);
        }

        session('admin', null);
        cookie('admin', null);

        Cache::flush();

        return api_response(200, '', []);
    }
}
